package at.ac.tuwien.mg.wh.client;

import java.util.List;

import javax.naming.InitialContext;

import org.activiti.engine.delegate.BpmnError;
import org.activiti.engine.delegate.DelegateExecution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import at.ac.tuwien.mg.wh.WarehouseBeanRemote;
import at.ac.tuwien.mg.wh.dto.ItemDTO;
import at.ac.tuwien.mg.wh.exception.WarehouseException;

public class BookingClient extends Client {

	private static Logger log = LoggerFactory.getLogger(BookingClient.class);

	@SuppressWarnings("unchecked")
	@Override
	public void execute(DelegateExecution execution) throws Exception {


		InitialContext ctx = new InitialContext();
		WarehouseBeanRemote bean = lookupStateless(ctx);
		
		//////
		List<ItemDTO> toBook = (List<ItemDTO>) execution.getVariable("toBook");
		Long userId = toLong(execution.getProcessInstanceId().toString());
		
		try{
			bean.bookItems(toBook, userId);
			
			// TEST
			if((Boolean) execution.getVariable("throwError")){
				execution.setVariable("throwError", false);
				throw new WarehouseException();
			}	
			//
			
			log("[BOOKING]\nBooked: "+toBook+" for user: "+userId);	
			
		}catch(WarehouseException e){
			log("ERROR: Not enough items on stock, retries lookup and booking "+toBook+" for user: "+userId);
			throw new BpmnError("NotEnoughOnStock");
		}
		
		
		//////
		
		closeContext(ctx);
	}
}
